home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!news
- From: Norman Bullen <nbullen@ix.netcom.com>
- Newsgroups: comp.lang.c
- Subject: Re: function to format float number
- Date: Wed, 06 Mar 1996 19:52:15 -0800
- Organization: Black Cat Associates
- Message-ID: <313E5D6F.4FD6@ix.netcom.com>
- References: <367cc$0321.121@news.express.ca>
- NNTP-Posting-Host: ple-ca9-19.ix.netcom.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-NETCOM-Date: Wed Mar 06 9:49:34 PM CST 1996
- X-Mailer: Mozilla 2.0 (Win16; I)
-
- Gary Chan wrote:
- >
- > I need a function to convert a floating point number to a formatted
- > dollar value string. Eg. 1234 becomes $1,234.00
- >
- >
- > *******************
- > Thanks in advance.
- Are you really sure you want to store dollar values in a float (or even
- double) variable? Neither one can EXACTLY represent a value of 0.01!
- Those round-off errors can really add up. I would suggest you use int or
- long (depending upon the maximum value you need) and store number of
- CENTs.
- In that case your function might be:
- void cformat(long n, char *buff)
- { int i;
- i = sprintf(buff, "%03ld", n);
- buff[i+2] = '\0';
- buff[i+1] = buff[i-1]; i--;
- buff[i+1] = buff[i-1]; i--;
- buff[i+1] = '.';
- while (i>0) {
- buff[i] = buff[i-1]; i--;
- }
- buff[0] = '$';
- }
-
- I didn't put in code to insert commas; something left for you to do.
-